package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送手机短信验证码
     *
     * @param user
     * @return
     */

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //获取手机号
        String phone = user.getPhone();

        if (StringUtils.isNotEmpty(phone)) {
            //生成随机的4位验证码
            Integer code = ValidateCodeUtils.generateValidateCode(4);
            //调用阿里云API发送短信
            //   SMSUtils.sendMessage();
            //将生成的验证码保存起到Session
         //   session.setAttribute(phone, code);

            //将生成的验证码缓存到redis中，并且设置有效期为5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

            return R.success("手机验证码短信发送成功");
        }

        return R.success("手机验证码短信发送失败");
    }

    @PostMapping("/login")
    public R<String> login(@RequestBody User user, HttpSession session) {

        // session.setAttribute("user",user.getPhone());

        /**
         * 从redis中获取验证码
         */
        redisTemplate.opsForValue().get(user.getPhone());
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, user.getPhone());
        User userServiceOne = userService.getOne(queryWrapper);
   //     log.info("+++++++++aaa++" + userServiceOne.toString());

        if (userServiceOne == null) {
            userService.save(user);
        }

        session.setAttribute("user", userServiceOne.getId());
               //如果用户登录成功删除redis中缓存的验证码
                redisTemplate.delete(user.getPhone());

        return R.success("登录成功");
    }

    /*    *
     * 退出登录
     * @return

     */
    @PostMapping("/loginout")
    public R<String> loginOut(HttpSession session) {

        session.removeAttribute("user");


        return R.success("退出成功");


    }
}
